package com.fuze.questionnaire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fuze.questionnaire.domain.dto.SurveyDTO;
import com.fuze.questionnaire.domain.entity.Options;
import com.fuze.questionnaire.domain.entity.Problem;
import com.fuze.questionnaire.domain.entity.ProblemOptionsRelated;
import com.fuze.questionnaire.domain.entity.ProjectType;
import com.fuze.questionnaire.mapper.OptionsMapper;
import com.fuze.questionnaire.mapper.ProblemMapper;
import com.fuze.questionnaire.mapper.ProblemOptionsRelatedMapper;
import com.fuze.questionnaire.mapper.ProjectTypeMapper;
import com.fuze.questionnaire.service.QuestionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sepc_
 * @date 11/26/2021 15:11
 * 问卷问题相关的业务逻辑的具体实现
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class QuestionServiceImpl implements QuestionService {

    final ProblemMapper problemMapper;

    final ProjectTypeMapper projectTypeMapper;

    final OptionsMapper optionsMapper;

    final ProblemOptionsRelatedMapper problemOptionsRelatedMapper;

    @Override
    public List<SurveyDTO> query(Integer projectTypeId) {
        // 构建问题的查询条件
        QueryWrapper<Problem> qw = new QueryWrapper<>();
        // 按照问卷问题的大类查询
        qw.eq(Problem.COL_PROJECT_TYPE_ID, projectTypeId);
        qw.orderByDesc(Problem.COL_SORTED);
        List<Problem> problems = problemMapper.selectList(qw);
        // 这个ArrayList用于构建问题列表
        List<SurveyDTO> list = new ArrayList<>(problems.size());
        // 遍历所有查询出来的问题
        problems.forEach(p -> {
            // 构建需要展示的问题
            SurveyDTO survey = new SurveyDTO();
            Integer problemId = p.getId();
            survey.setProblemId(problemId);
            survey.setProblem(p.getProblem());
            survey.setProblemType(p.getProjectTypeId());
            survey.setQuestionType(p.getQuestionType());
            survey.setSuperiorProblemId(p.getSuperiorProblemId());
            // 通过问题的id去查询关联的问题答案
            QueryWrapper<ProblemOptionsRelated> wrapper = new QueryWrapper<>();
            wrapper.eq(ProblemOptionsRelated.COL_PROBLEM_ID, problemId);
            // 多对多关联，查出来的是一个桥表，再遍历查询全部的答案
            List<ProblemOptionsRelated> relatedList = problemOptionsRelatedMapper.selectList(wrapper);
            ArrayList<Options> optionsList = new ArrayList<>();
            relatedList.forEach(r -> {
                Integer optionsId = r.getOptionsId();
                // 构建答案列表
                optionsList.add(optionsMapper.selectById(optionsId));
            });
            survey.setOptionsList(optionsList);
            list.add(survey);
        });
        return list;
    }

    @Override
    public List<ProjectType> listProjectType() {
        return projectTypeMapper.selectList(null);
    }
}
